package com.ext.aic.utils;

import org.jsoup.Jsoup;
import org.jsoup.safety.Safelist;

public class FilteringUtils {

    private static volatile FilteringUtils instance;

    public static FilteringUtils getInstance() {
        if (instance == null) {
            synchronized (FilteringUtils.class) {
                if (instance == null) {
                    instance = new FilteringUtils();
                }
            }
        }
        return instance;
    }

    public String toText(String content) {
        String result = Jsoup.clean(content, Safelist.none());
        return result.replaceAll("#", "").trim();
    }

    // 主过滤方法：自动检测并去除重复的循环节
    public String filterRepeatedContent(String input) {
        if (input == null || input.length() < 2) {
            return input;
        }

        int[] prefix = computePrefixArray(input);
        int patternLength = input.length() - prefix[input.length() - 1];

        // 验证是否满足重复模式条件
        if (prefix[input.length() - 1] > 0
                && (input.length() % patternLength == 0)) {
            return input.substring(0, patternLength);
        }
        return input;
    }

    // 计算KMP前缀数组（关键算法）
    private int[] computePrefixArray(String s) {
        int[] prefix = new int[s.length()];
        for (int i = 1; i < s.length(); i++) {
            int j = prefix[i - 1];
            // 通过回溯找到最长匹配前缀
            while (j > 0 && s.charAt(i) != s.charAt(j)) {
                j = prefix[j - 1];
            }
            // 扩展匹配长度
            if (s.charAt(i) == s.charAt(j)) {
                j++;
            }
            prefix[i] = j;
        }
        return prefix;
    }

    public String html(String content) {
        content = content.replaceAll("(&lt;br\\s*/?&gt;|<br\\s*/?>)", "\n");
        content = content.replaceAll("&#9;", "\t");
        content = content.replaceAll("&nbsp;", " ");
        content = content.replaceAll("&amp;", "&");
        content = content.replaceAll("#9;", "");
        content = content.replaceAll("\n+", "\n");
        return content;
    }
}
